<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-12 14:38:48
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Comprehensive;


use App\Http\Services\Service;
use App\Repositories\ShiftRepository;
use App\Repositories\UserRepository;
use Illuminate\Support\Facades\Hash;

/**
 * @property UserRepository $user
 * @author sunkaiyuan
 */
class ShiftService extends Service
{
    public $details;
    public function __construct(ShiftRepository $repository)
    {
        $this->repository = $repository;
    }
    public function list()
    {
        $data = $this->repository->condition(request())->getGrid();
        return $data;
    }
    public function info()
    {
        return $this->repository->with(["users" => ['department']])->condition(request())->getOne();
    }
    protected function save()
    {
        $data = request()->toArray();
        $ids = array_map(function ($v) {
            return $v['id'];
        }, $data['users'] ?? []);
        $shift_data = $this->repository->autosave($data);
        $shift_data->users?->filter(function ($v) use ($ids) {
            if (!in_array($v->id, $ids)) {
                $v->shift_id = 0;
                $v->save();
            }
        });
        return $shift_data;
    }

    protected function delete()
    {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v) {
            if ($v->user()->count() > 0) {
                fail("该班次已被部分员工使用！无法删除!");
            }
            $v->delete();
        });
    }
}
